<template>
    <div class="home-wrapper">
        <project-menu :detail="projectDetail" :pid="projectId"></project-menu>
        <div class="filters-wrapper">
            <div class="title total_title">定向包
                <router-link v-if="projectDetail.status == 1" :to="{path:'/audiencepackage/' + projectId + '/0' }">
                    <el-button class="fr" type="primary" size="small">新建定向包</el-button>
                </router-link>
            </div>
            <el-table :data="directionaldata" border
                :header-cell-style="{'text-align':'center','background':'#f7f7f7','color':'#666'}"
                style="width: 100%;margin-top: 10px" ref="multipleTable" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <el-table-column prop="name" label="定向包名称" align="center">
                </el-table-column>
                <el-table-column prop="description" label="定向描述" align="center">
                </el-table-column>
                <el-table-column prop="update_time" label="更新时间" align="center">
                </el-table-column>
                <el-table-column prop="operation" label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button v-if="projectDetail.status == 1" size="mini" @click="preview(scope.row)">预览
                        </el-button>
                        <el-button v-if="projectDetail.status == 1" style="margin-left: 5px;" size="mini"
                            @click="copy(scope.row)">复制</el-button>
                        <el-button v-if="projectDetail.status == 1" @click="modify(scope.row)" style="margin-left: 5px;"
                            size="mini" type="primary">修改</el-button>
                        <el-button v-if="projectDetail.status == 1" style="margin-left: 5px;" size="mini" type="danger"
                            @click="del([scope.row])">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-row type="flex" justify="end" style="margin-top: 20px">
                <el-button v-if="projectDetail.status == 1" size="small" @click="toggleSelection(directionaldata)">全选
                </el-button>
                <el-button v-if="projectDetail.status == 1" size="small" type="danger" @click="delSelect">删除</el-button>
            </el-row>
            <el-row type="flex" justify="end" style="margin-top: 20px;">
                <el-pagination background layout="prev, pager, next" :current-page.sync="curPage" :total="total"
                    :page-size="pageSize" @current-change="handleCurrentChange($event)">
                </el-pagination>
            </el-row>
            <el-drawer class="plTitle_wrap" title="定向包预览" :visible.sync="previewShow" :wrapperClosable="false">
                <div class="info-area">
                    <div class="module-info">
                        <div class="module-title">基本信息</div>
                        <div class="module-content">
                            <div class="info-row clearfix">
                                <div class="row-title">定向包名称</div>
                                <div class="row-value">{{audiencedata.name}}</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">定向包描述</div>
                                <div class="row-value">{{audiencedata.description}}</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">定向包类型</div>
                                <div class="row-value">{{audiencedata.landing_type=='EXTERNAL'?'落地页':'电商店铺推广'}}</div>
                            </div>
                        </div>
                    </div>
                    <div class="module-info">
                        <div class="module-title">投放范围</div>
                        <div class="module-content">
                            <div class="info-row clearfix">
                                <div class="row-title">投放范围</div>
                                <div class="row-value">{{audiencedata.delivery_range=='DEFAULT'?'默认':'穿山甲'}}</div>
                            </div>
                        </div>
                    </div>
                    <div class="module-info">
                        <div class="module-title">用户定向</div>
                        <div class="module-content">
                            <div class="info-row clearfix">
                                <div class="row-title">地域</div>
                                <div class="row-value">
                                  {{audiencedata.district}} 
                                </div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">性别</div>
                                <div class="row-value">{{type_gender[audiencedata.gender]}}</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">年龄</div>
                                <div class="row-value">{{formatShow('age', audiencedata.age)}}</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">抖音达人</div>
                                <div class="row-value">不限</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">精选流量包</div>
                                <div class="row-value">不限</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">平台</div>
                                <div class="row-value">{{formatShow('platform', audiencedata.platform)}}</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">文章分类</div>
                                <div class="row-value">{{formatShow('article_category', audiencedata.article_category)}}</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">网络</div>
                                <div class="row-value">{{formatShow('ac', audiencedata.ac)}}</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">过滤已转化用户</div>
                                <div class="row-value">{{formatShow('hide_if_converted', audiencedata.hide_if_converted)}}</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">运营商</div>
                                <div class="row-value">{{formatShow('carrier', audiencedata.carrier)}}</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">新用户</div>
                                <div class="row-value">{{formatShow('activate_type', audiencedata.activate_type)}}</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">手机品牌</div>
                                <div class="row-value">{{formatShow('device_brand', audiencedata.device_brand)}}</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">手机价格</div>
                                <div class="row-value">{{this.audiencedata.launch_price[0] + '元' + ' ~ ' + this.audiencedata.launch_price[1] + '元'}}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="module-info">
                        <div class="module-title">预算与出价</div>
                        <div class="module-content">
                            <div class="info-row clearfix">
                                <div class="row-title">出价方式</div>
                                <div class="row-value">{{formatShow('smart_bid_type', audiencedata.smart_bid_type)}}</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">投放方式</div>
                                <div class="row-value">{{formatShow('flow_control_mode', audiencedata.flow_control_mode)}}</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">预算类型</div>
                                <div class="row-value">{{formatShow('budget_mode', audiencedata.budget_mode)}}</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">预算</div>
                                <div class="row-value">{{audiencedata.budget}}</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">投放时间</div>
                                <div class="row-value">
                                <span v-if="audiencedata.schedule_type=='SCHEDULE_FROM_NOW'">
                                  从今天开始长期投放
                                </span>
                                <span v-else>
                                {{formatArray(audiencedata.PutTime, '~')}}
                                </span>
                                </div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">投放时段</div>
                                <div class="row-value">
                                    <span v-if="audiencedata.PeriodCur==1">
                                       不限 
                                    </span>
                                    <p v-for="(item, index) in audiencedata.schedule_format_time" :key="index">
                                        <span class="tip-text">{{item.weeks}}</span>
                                        <span>
                                          <span v-for="(time, index2) in item.points" :key="index2">
                                            {{time.time}}、
                                          </span>
                                        </span>
                                    </p>
                                </div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">付费方式</div>
                                <div class="row-value">{{formatShow('pricing', audiencedata.pricing)}}</div>
                            </div>
                            <div class="info-row clearfix">
                                <div class="row-title">目标转化出价</div>
                                <div class="row-value">{{audiencedata.cpa_bid}}</div>
                            </div>
                        </div>
                    </div>
                </div>
            </el-drawer>
        </div>
    </div>
</template>

<script>
    import {
        pageParams, parseObject,audience_config
    } from '@/settings'
    import cityJson from '@/util/city.json'

    const COLUMN_COUNT = 48
    let WEEKS = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
    export default {
        data() {
            return {
                projectDetail: {},
                projectId: 0,
                pageSize: pageParams.pageSize,
                curPage: 1,
                total: 0,
                directionaldata: [],
                multipleSelection: [],
                previewShow: false,
                audienceDetail:[],
                audiencedata: {
                    id: 0,
                    name: '',
                    description: '',
                    delivery_range: 'DEFAULT',
                    landing_type: 'EXTERNAL',
                    district: 'NONE',
                    citys: [], // 临时保存 需要根据district来设置city值
                    countys: [], // 临时保存 需要根据district来设置city值
                    city: [],
                    gender: 'NONE',
                    age: [],
                    location_type_county: 'CURRENT',
                    location_type_city: 'CURRENT',
                    location_type: 'CURRENT',
                    tiktok: 1,
                    superior_popularity_type: 'NONE',
                    platform: [],
                    ac: [],
                    hide_if_converted: 'NO_EXCLUDE',
                    carrier: [],
                    activate_type: [],
                    budget_mode:'BUDGET_MODE_DAY',
                    PutTime: [], // 临时保存时间
                    article_category: [],
                    start_time: '',
                    end_time: '',
                    smart_bid_type: 'SMART_BID_CUSTOM', // 出价方式
                    flow_control_mode: 'FLOW_CONTROL_MODE_FAST',
                    budget: '', // 广告预算
                    cpa_bid: '',
                    pricing: 'PRICING_OCPM',
                    adjust_cpa:false,
                    precostinpt:'',
                    schedule_type: 'SCHEDULE_FROM_NOW',
                    schedule_format_time: [],
                    schedule_time: new Array(24*2*7 + 1).join('0'),
                    device_brand: [], // 受众手机品牌
                    launch_price: [0, 11000],
                    PeriodCur: 1 
                },
                type_gender: {
                 'NONE': '不限',
                 'GENDER_FEMALE': '男',
                 'GENDER_MALE': '女',
                },
                selectAllData: audience_config,
            }
        },
        created() {
            this.projectId = this.$router.currentRoute.params.id
        },
        mounted() {
            // this.projectId = this.$router.currentRoute.params.id
            this.loadData()
        },
        methods: {
            loadData() {
                this.$axios.get('/project/detail', {
                        projectid: this.projectId
                    })
                    .then(e => {
                        this.projectDetail = e.data
                    })
                this.loadDirectionalList({})
            },
            loadDirectionalList(param) {
                param['number'] = this.pageSize
                param['projectid'] = this.projectId
                if (!param['page']) {
                    param['page'] = 1
                }
                this.curPage = param['page']
                this.$axios.get('/directional/list', param)
                    .then(e => {
                        this.directionaldata = e.data.items
                        this.total = e.data.total
                        console.log('定向包', e.data)
                    })
            },
            handleCurrentChange(val) {
                this.loadDirectionalList({
                    page: val
                })
            },
            copy(item) {
                let param = {
                    id: item.id
                }
                this.$confirm('此操作将复制该项, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.post('/directional/copy', param)
                        .then(() => {
                            this.loadDirectionalList({})
                            this.$message({
                                type: 'success',
                                message: '复制成功!'
                            })
                        })
                }).catch(() => {})
            },
            modify(item) {
                this.$router.push({
                    path: '/audiencepackage/' + this.projectId + '/' + item.id
                })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            toggleSelection(rows) {
                if (rows) {
                    rows.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row)
                    });
                } else {
                    this.$refs.multipleTable.clearSelection()
                }
            },
            delSelect() {
                // console.log(this.multipleSelection)
                if (this.multipleSelection.length <= 0) {
                    this.$message({
                        type: 'error',
                        message: '没有选择项目!'
                    })
                    return
                }
                this.del(this.multipleSelection)
            },
            del(items) {
                // console.log(items)
                let ids = []
                for (const v in items) {
                    ids.push(items[v].id)
                }
                let param = {
                    ids: ids
                }
                this.$confirm('此操作将删除该项, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.post('/directional/delete', param)
                        .then(() => {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            })
                            this.loadDirectionalList({})
                        })
                }).catch(() => {})
            },
            preview(item) {
                this.loading = true
                this.$axios.get('/directional/detail', {
                        project_id: this.projectId,
                        id: item.id
                    })
                    .then(e => {
                        this.previewShow = true
                        this.loading = false
                        this.audiencedata = parseObject(this.audiencedata, e.data)
                        this.audiencedata.adjust_cpa = this.audiencedata.adjust_cpa && this.audiencedata.adjust_cpa == 1
                        if (!this.putmanual && this.audiencedata.adjust_cpa) {
                            this.audiencedata.precostinpt = e.data['cpa_bid']
                            this.audiencedata.cpa_bid = ''
                        }
                        if (this.audiencedata.district == 'CITY') {
                            this.audiencedata.citys = this.audiencedata.city
                            this.audiencedata.location_type_city = this.audiencedata.location_type
                        } else if (this.audiencedata.district == 'COUNTY'){
                            this.audiencedata.countys = this.audiencedata.city
                            this.audiencedata.location_type_county = this.audiencedata.location_type
                        }
                        this.articleCur = this.audiencedata.article_category.length > 0 ? 2 : 1
                        this.phoneCur = this.audiencedata.device_brand.length > 0 ? 2 : 1
                        if (e.data.schedule_time && /^0+$/.test(e.data.schedule_time)) {
                            this.audiencedata.PeriodCur = 1 
                        } else {
                            this.audiencedata.PeriodCur = 2
                        }
                        // 时段问题
                        this.audiencedata.schedule_format_time = this.formatTimeStr(e.data.schedule_time)
                        if (!this.audiencedata.age) {
                            this.audiencedata.age = []
                        }
                        if (!this.audiencedata.platform) {
                            this.audiencedata.platform = []
                        }
                        if (!this.audiencedata.ac) {
                            this.audiencedata.ac = []
                        }
                        if (!this.audiencedata.carrier) {
                            this.audiencedata.carrier = []
                        }
                        if (!this.audiencedata.activate_type) {
                            this.audiencedata.activate_type = []
                        }
                        if (!this.audiencedata.article_category) {
                            this.audiencedata.article_category = []
                        }
                        if (!this.audiencedata.device_brand) {
                            this.audiencedata.device_brand = []
                        }
                        //PutTime
                        this.audiencedata.PutTime = []
                        if (this.audiencedata.start_time && this.audiencedata.end_time) {
                            this.audiencedata.PutTime.push(this.audiencedata.start_time)
                            this.audiencedata.PutTime.push(this.audiencedata.end_time)
                        }
                        // console.log('this.audiencedata', this.audiencedata, e.data)
                        let cityids = []
                        if (this.audiencedata.district=='NONE') {
                            this.audiencedata.district = '不限'
                        } else if(this.audiencedata.district=='CITY'){
                            cityids  = this.audiencedata.citys
                        } else if(this.audiencedata.district=='COUNTY') {
                            cityids = this.audiencedata.countys
                        }
                        if (cityids.length > 0) {
                            let citys = []
                            cityids.forEach(i => {
                                let city = null
                                for(let k in cityJson) {
                                    if (k == i) {
                                      city = cityJson[k]
                                      break
                                    }
                                }
                                if (city) {
                                  citys.push(city.name)
                                } else {
                                  citys.push('未知错误')
                                }
                            })
                            this.audiencedata.district = this.formatArray(citys)
                        }
                    })
            },
            findKey(data, value, compare = (a, b) => a === b) {
                return Object.keys(data).find(k => compare(data[k], value))
            },
            formatShow(field, val) {
                let data = this.selectAllData[field]
                if (data == undefined) {
                    console.error('error', field, val, data)
                    return 'error'
                }
                let ret = ''
                if (Array.isArray(val)) {
                    ret = []
                    val.forEach(e => {
                        let v = this.findKey(data, e)
                        ret.push(v)
                    })
                    if (ret.length === 0) {
                        ret = '不限'
                    }
                } else {
                    ret = this.findKey(data, val)
                }
                if (Array.isArray(ret)) {
                  ret = this.formatArray(ret)
                }
                return ret
            },
            formatTimeStr(time) {
              let val = time.split('')
              let datas = []
              for (let i = 0; i < val.length; i++) {
                  if (val[i] == '1') {
                      datas.push(i)
                  }
              }
              datas = datas.sort((a, b) => {
                  return a - b
              })
              let result = []
              datas.forEach(e => {
                  let id = parseInt(e / COLUMN_COUNT)
                  let pos = e % COLUMN_COUNT + 1
                  let ele = result.find( ele => {
                      return ele.id == id
                  })
                  if (ele) {
                      ele.times.push(pos)
                  } else {
                      result.push({id: id, weeks: WEEKS[id], times: [pos], points:[]})
                  }
              })
              // 对时间点进行处理
              result.forEach(ele => {
                  let stime = ele.times[0]
                  let etime = ele.times[0]
                  let pos = 0
                  
                  for (let i = 0; i < ele.times.length; i++) {
                      if (stime + pos == ele.times[i]) {
                          etime = ele.times[i]
                          pos = pos + 1
                      } else {
                          ele.points.push({time: this.formatTime(stime , etime) })
                          stime = ele.times[i]
                          etime = ele.times[i]
                          pos = 1
                      }
                  }
                  ele.points.push({time: this.formatTime(stime , etime)})
              })
              if (result.length === 0) {
                return '不限'
              }
              return result
            },
            formatTime(stime, etime) {
                if (stime > COLUMN_COUNT) {
                    stime = stime % COLUMN_COUNT
                }
                let s = (stime-1) * 30
                let e = (etime * 30)
                const formatObj1 = {
                    h: parseInt(s / 60),
                    i: s % 60
                }
                let time_str = this._format(formatObj1)
                if (!etime) {
                    return time_str
                }
                const formatObj2 = {
                    h: parseInt(e / 60),
                    i: e % 60
                }
                time_str = time_str + '~' + this._format(formatObj2)
                // console.log(time_str)
                return time_str
            },
            _format(formatObj) {
                const format = '{h}:{i}'
                const time_str = format.replace(/{([hi])+}/g, (result, key) => {
                    const value = formatObj[key]
                    return value.toString().padStart(2, '0')
                })
                return time_str
            },
            formatArray(arr, splitStr) {
              if (!splitStr) {
                splitStr = "、"
              }
              return arr.join(splitStr)
            }
        },
    }
</script>
